import { _decorator, Component, director, instantiate, Node, Prefab } from 'cc';
import { NetWorkManager } from '../Global/NetWorkManager';
import { ApiMsgEnum, IApiPlayerListRes, IMsgGameStart, IMsgRoom, IState } from '../Common';
import { PlayerMgr } from '../UI/PlayerMgr';
import DataManager from '../Global/DataManager';
import { SceneEnum } from '../Enum';
import { deepClone } from '../Utils';
const { ccclass, property } = _decorator;

@ccclass('RoomManager')
export class RoomManager extends Component {
    @property({type:Node})
    playerContainer:Node;
    @property({type:Prefab}) 
    playerPrefab:Prefab;

    protected onLoad(): void {
        NetWorkManager.Instance.listenMsg(ApiMsgEnum.MsgGameStart,this.handleGameStart,this);
        NetWorkManager.Instance.listenMsg(ApiMsgEnum.MsgRoom,this.renderPlayers,this);
    }

    start() {
        this.renderPlayers({room:DataManager.Instance.roomInfo})
    }

    protected onDestroy(): void {
        NetWorkManager.Instance.unlistenMsg(ApiMsgEnum.MsgGameStart,this.handleGameStart,this);
        NetWorkManager.Instance.unlistenMsg(ApiMsgEnum.MsgRoom,this.renderPlayers,this);
    }
 
    renderPlayers({room:{players:list}}:IMsgRoom){
        for(const c of this.playerContainer.children){
            c.active = false;
        }
        while(list.length>this.playerContainer.children.length){
            const playerNode = instantiate(this.playerPrefab);
            playerNode.setParent(this.playerContainer);
        }
        for(let i=0;i<list.length;i++){
            const data = list[i];
            const player = this.playerContainer.children[i];
            player.getComponent(PlayerMgr).init(data)
        }
    }

    async handleLeaveRoom(){
        const {success,error,res} = await NetWorkManager.Instance.callApi(ApiMsgEnum.ApiRoomLeave,{}) 
        if(!success){
            console.log("LeaveRoom error!",error);
            return;
        }

        DataManager.Instance.roomInfo = null;
        director.loadScene(SceneEnum.Hall);
    }

    async handleStart(){
        const {success,error,res} = await NetWorkManager.Instance.callApi(ApiMsgEnum.ApiGameStart,{}) 
        if(!success){
            console.log("Start error!",error);
            return;
        }
    }

    async handleGameStart({state}:IMsgGameStart){
        DataManager.Instance.State = state;
        DataManager.Instance.lastState = deepClone(state);
        director.loadScene(SceneEnum.Battle);
    }

}


